<template>
  <div class="table" v-loading="loading">
    <div class="table-tools" v-if="title || $slots.tools">
      <span class="table-title" v-if="title">{{ title }}</span>
      <slot name="tools"></slot>
    </div>
    <el-table
      :data="tableData"
      border
      stripe
      v-bind="$attrs"
      v-on="$listeners"
      style="width:100%"
    >
      <el-table-column
        type="selection"
        width="50"
        align="center"
      ></el-table-column>
      <slot></slot>
    </el-table>
    <div class="table-page">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="total"
        :layout="pageLayout"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Table',
  props: {
    title: {
      type: String,
      default: ''
    },
    searchData: {
      type: Object,
      default: () => ({})
    },
    service: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      tableData: [],
      loading: false,
      pageSizes: [10, 20, 50, 100],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      pageLayout: 'total, sizes, prev, pager, next, jumper'
    }
  },
  methods: {
    async search(refresh = false) {
      try {
        if (refresh) {
          this.currentPage = 1
        }
        this.loading = true
        const pageData = {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        }
        const data = await this.service(this.searchData, pageData)
        const { rows, total } = data
        this.tableData = rows
        this.total = total
      } catch {
        this.clear()
      } finally {
        this.loading = false
      }
    },
    clear() {
      this.tableData = []
      this.total = 0
      this.currentPage = 1
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.search()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.search()
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'styles/common.scss';
.table {
  background-color: $colorWhite;
  border-radius: $borderRadius;
  .table-title {
    font-size: 16px;
    color: $colorText1;
    margin-right: 10px;
  }
  .table-tools {
    height: 50px;
    padding: 0 $horPadding;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .table-page {
    height: 50px;
    padding: 0 $horPadding;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}
</style>
